import React, { useState, useEffect } from 'react';
import { 
  Table, 
  Space, 
  Button, 
  Modal, 
  message, 
  Tag, 
  Typography,
  Empty,
  Card
} from 'antd';
import { DeleteOutlined, RollbackOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import axios from 'axios';
import { jwtDecode } from 'jwt-decode';

const { Title } = Typography;
const API_BASE_URL = 'http://localhost:8080/api';

// 辅助函数：从localStorage获取并解码token
const getCurrentUser = () => {
  try {
    const token = localStorage.getItem('token');
    if (token) {
      return jwtDecode(token);
    }
  } catch (error) {
    console.error("Failed to decode token", error);
    return null;
  }
  return null;
};

const Orders = () => {
  const [orders, setOrders] = useState([]);
  const [loading, setLoading] = useState(true);

  // 从后端获取订单列表
  const fetchOrders = async () => {
    try {
      setLoading(true);
      const currentUser = getCurrentUser();
      
      if (!currentUser || !currentUser.userId) {
          message.error('无法获取用户信息，请重新登录。');
          setLoading(false);
          return;
      }
      const userId = currentUser.userId;
      
      const token = localStorage.getItem('token');
      const response = await axios.get(`${API_BASE_URL}/orders/user/${userId}`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });
      setOrders(response.data);
    } catch (error) {
      console.error('Error fetching orders:', error);
      if (error.response && error.response.status === 403) {
        message.error('您没有权限查看此订单列表。');
      } else {
        message.error('获取订单列表失败');
      }
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchOrders();
  }, []);

  // 处理退票
  const handleRefund = async (orderNumber) => {
    try {
      await axios.put(`${API_BASE_URL}/orders/${orderNumber}/status`, null, {
        params: { status: 'REFUNDED' }
      });
      message.success('退票成功，退款将在1-3个工作日内到账');
      fetchOrders(); // 重新获取订单列表
    } catch (error) {
      console.error('Error refunding order:', error);
      message.error('退票失败，请重试');
    }
  };

  // 处理删除订单
  const handleDelete = async (orderId) => {
    try {
      const token = localStorage.getItem('token');
      await axios.delete(`${API_BASE_URL}/orders/${orderId}`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });
      message.success('订单删除成功');
      fetchOrders(); // 重新获取订单列表
    } catch (error) {
      console.error('Error deleting order:', error);
      message.error('订单删除失败，请重试');
    }
  };

  const columns = [
    {
      title: '订单编号',
      dataIndex: 'orderNumber',
      key: 'orderNumber',
    },
    {
      title: '电影',
      dataIndex: 'movieTitle',
      key: 'movieTitle',
    },
    {
      title: '影院',
      dataIndex: 'cinemaName',
      key: 'cinemaName',
    },
    {
      title: '场次',
      dataIndex: 'showtime',
      key: 'showtime',
    },
    {
      title: '座位',
      dataIndex: 'seats',
      key: 'seats',
    },
    {
      title: '总价',
      dataIndex: 'totalPrice',
      key: 'totalPrice',
      render: (price) => `¥${price.toFixed(2)}`,
    },
    {
      title: '订单状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => {
        const statusMap = {
          'PENDING': '待支付',
          'PAID': '已支付',
          'COMPLETED': '已完成',
          'CANCELLED': '已取消',
          'REFUNDED': '已退票'
        };
        const statusColors = {
          'PENDING': 'gold',
          'PAID': 'green',
          'COMPLETED': 'blue',
          'CANCELLED': 'red',
          'REFUNDED': 'purple'
        };
        return <Tag color={statusColors[status]}>{statusMap[status] || status}</Tag>;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (time) => new Date(time).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          {record.status === 'PAID' && (
            <Button
              type="primary"
              icon={<RollbackOutlined />}
              onClick={() => Modal.confirm({
                title: '确认退票？',
                icon: <ExclamationCircleOutlined />,
                content: '退票后将无法恢复，是否继续？',
                okText: '确认退票',
                cancelText: '取消',
                onOk: () => handleRefund(record.orderNumber)
              })}
            >
              退票
            </Button>
          )}
          <Button
            type="danger"
            icon={<DeleteOutlined />}
            onClick={() => {
              console.log("Delete button clicked for order ID:", record.id);
              handleDelete(record.id); // 直接调用 handleDelete，跳过 Modal.confirm
            }}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <Card>
        <Title level={2}>我的订单</Title>
        
        {orders.length === 0 ? (
          <Empty
            description="暂无订单"
            image={Empty.PRESENTED_IMAGE_SIMPLE}
          />
        ) : (
          <Table
            columns={columns}
            dataSource={orders}
            rowKey="orderNumber"
            loading={loading}
            pagination={{
              defaultPageSize: 10,
              showSizeChanger: true,
              showTotal: (total) => `共 ${total} 条订单`,
            }}
          />
        )}
      </Card>
    </div>
  );
};

export default Orders; 